package com.qc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.qc.dto.CookDetail;
import com.qc.dto.DishIngredientsAndRecipe;
import com.qc.enity.*;
import com.qc.mapper.*;
import com.qc.service.IDishService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 菜谱相关业务层
 */

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private RecipeProcedureMapper recipeProcedureMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private DishTypeMapper dishTypeMapper;

    /** 获取菜谱列表 */
    @Override
    public IPage<Dish> dishList(Page page) {

        //一个简单的分页查询，获取dish表信息
        IPage data = dishMapper.selectPage(page, null);

        //获取查询结果的total
        page.setTotal(data.getTotal());
        //获取当前page的current
        long current = page.getCurrent();
        //前端所传的页码可能超过最大页码数
        Page updatePage = this.pagination(page);

        //如果current被修改，重新查询
        if (current != updatePage.getCurrent()){
            //一个简单的分页查询，获取dish表信息
            data = dishMapper.selectPage(updatePage, null);
        }
        return data;
    }

    /** 搜索菜谱 */
    @Override
    public IPage<Dish> dishSelect(Page page, String name) {

        //一个简单的模糊查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Dish::getDishName, name);
        IPage data = dishMapper.selectPage(page, queryWrapper);

        //获取查询结果的total
        page.setTotal(data.getTotal());
        //获取当前page的current
        long current = page.getCurrent();
        //如果前端所传的页码可能超过最大页码数
        Page updatePage = this.pagination(page);

        //如果current被修改，重新查询
        if (current != updatePage.getCurrent()){
            //一个简单的模糊查询
            data = dishMapper.selectPage(updatePage, queryWrapper);
        }

        return data;
    }

    /** 菜品做法 */
    @Override
    public CookDetail dishCook(Integer dishId) {

        //一、通过dishId获取该菜品
        Dish dish = dishMapper.selectById(dishId);

        //二、获取该菜品所需的食材和对应的食材用量
        //Recipe和DishIngredients进行连表查询，获取食材和对应的食材用量
        MPJLambdaWrapper<Recipe> wrapper = new MPJLambdaWrapper<Recipe>()
                .select(DishIngredients::getIngredientsName)
                .select(Recipe::getIngredientsAmount)
                .leftJoin(DishIngredients.class, DishIngredients::getIngredientsId, Recipe::getIngredientsId)
                .eq(Recipe::getDishId, dishId);
        //连表查询，返回自定义DishIngredientsAndRecipe DTO对象
        List<DishIngredientsAndRecipe> list = recipeMapper.selectJoinList(DishIngredientsAndRecipe.class, wrapper);

        //三、获取该菜品做法步骤
        LambdaQueryWrapper<RecipeProcedure> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecipeProcedure::getDishId, dishId).orderByAsc(RecipeProcedure::getProcedureNo);
        List<RecipeProcedure> recipeProcedures = recipeProcedureMapper.selectList(queryWrapper);
        //将recipeProcedures对象中前端用不到的数据设为null
        for (RecipeProcedure obj : recipeProcedures) {
            obj.setDishId(null);
            obj.setProcedureId(null);
            obj.setProcedureNo(null);
        }
        //创建cookDetail对象，接收数据
        CookDetail cookDetail = new CookDetail();
        cookDetail.setDish(dish);
        cookDetail.setDishIngredientsAndRecipes(list);
        cookDetail.setRecipeProcedures(recipeProcedures);

        return cookDetail;
    }

    /** 本周佳作（每周随机推荐一个菜品） */
    @Override
    public Dish dishCommend(Integer dishId) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("dish_dianzan");
        List<Dish> dishList = this.list(queryWrapper);
        return dishList.get(0);
    }

    /**根据typeId查Dish */
    @Override
    public List<Dish> getDishByTypeId(Integer typeId) {

        //获取该类型所包含的菜品列表
        //Dish和DishType进行连表查询，获取菜品所在分类和具体信息
        MPJLambdaWrapper<DishType> wrapper = new MPJLambdaWrapper<DishType>()
                .select(Dish::getDishId)
                .select(Dish::getDishName)
                .select(Dish::getDishPicture)
                .select(Dish::getDishDescribe)
                .select(Dish::getDishTip)
                .leftJoin(Dish.class, Dish::getDishId, DishType::getDishId)
                .eq(DishType::getTypeId, typeId);
        //连表查询，返回dish对象
        List<Dish> list = dishTypeMapper.selectJoinList(Dish.class, wrapper);

        return list;
    }

    @Override
    public Integer addDishList(Dish dish) {
        QueryWrapper<Dish> queryWrapper=new QueryWrapper();
        Integer count = dishMapper.selectCount(queryWrapper);
        Dish dish2 = new Dish();
        count = count  + 1 ;
        dish2.setDishId(count);
        dish2.setDishName(dish.getDishName());
        dish2.setDishTip(dish.getDishTip());
        dish2.setDishPicture(dish.getDishPicture());
        dish2.setDishDescribe(dish.getDishDescribe());
        dish2.setDishDianzan(0);
        int dishRows = dishMapper.insert(dish2);
        return dishRows;
    }

    @Override
    public Integer addDishDianZan(Integer dishId) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dishId);
        Dish dish = this.getOne(queryWrapper);
        if (dish == null) {
            // 如果没有查询到对应的菜品信息，可以根据业务需求进行处理，这里简单返回 null
            return null;
        }
        Integer dishDianzan = dish.getDishDianzan();

        if (dishDianzan == null) {
            // 如果点赞数为 null，将其置为 0
            dishDianzan = 0;
        }
        dishDianzan++;
        dish.setDishDianzan(dishDianzan);
        int i = dishMapper.updateById(dish);
        return i ;
    }

    @Override
    public List<Dish> descDishList(Page page) {
        //一个简单的分页查询，获取dish表信息
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("dish_dianzan");
        List<Dish> dishList = this.list(queryWrapper);
        return dishList;
    }

    @Override
    public Dish dishIdChaXun(Integer dishId) {
        Dish dish = new Dish();
        dish.setDishId(dishId);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>(dish);
        List<Dish> s = dishMapper.selectList(queryWrapper);
        System.out.println(s.get(0));
        if (s.toString() != "[]" ) {
            return s.get(0);
        }
        return null;
    }

    @Override
    public Integer updateDishById(Dish dish) {
        int i = dishMapper.updateById(dish);
        return i;
    }

    @Override
    public List commendAll() {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("dish_dianzan");
        List<Dish> dishList = this.list(queryWrapper);
        return dishList;
    }

    @Override
    public Integer deleteDishList(Integer dishId) {
        int result = dishMapper.deleteById(dishId);
        return result;
    }
    /**
     * update dish by id
     */

    /** 处理页码超出最大页码数问题 */
    public Page pagination(Page page){

        //前端所传的页码可能超过最大页码数
        long total = page.getTotal();
        long size = page.getSize();
        long current = page.getCurrent();

        if (total / size < current){
            //如果超过了，将当前页码修改为最大页码
            page.setCurrent((long) Math.ceil((double) total / size));
        }

        return page;

    }

    /** 获取随机本周佳作 */
    public Dish weekDish(Integer dishId){
        //获取生成随机数对象
        Random random = new Random();
        //使用set集合，保证新生成的随机数与原来的不一致
        Set<Integer> set = new LinkedHashSet<>();
        set.add(dishId);
        while (set.size() < 3){
            set.add(random.nextInt(150) + 1);
        }
        Object[] array = set.toArray();
        Integer newDishId = (Integer) array[2];
        //获取新的随机菜品
        Dish dish = dishMapper.selectById(newDishId);

        return dish;
    }

}
